import 'package:flutter/material.dart';
import 'package:mirror/AppStyle.dart';
import 'package:mirror/CommonLoading.dart';
import 'package:mirror/api/MessageApi.dart';
import 'package:mirror/bean/GroupBean.dart';
import 'package:mirror/bean/GroupBean2.dart';
import 'package:mirror/page/home/pages/message/ChatPage.dart';
import 'package:mirror/widget/EmptyWidget.dart';

class ExistGroupPage extends StatefulWidget {
  const ExistGroupPage({super.key});

  @override
  State<ExistGroupPage> createState() => _ExistGroupPageState();
}

class _ExistGroupPageState extends State<ExistGroupPage> {
  List<GroupBean> list = [];

  @override
  void initState() {
    super.initState();
    refresh();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          "所有群聊",
          style: TextStyle(fontSize: 16),
        ),
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
                child: list.isEmpty
                    ? const EmptyWidget()
                    : Padding(
                        padding: const EdgeInsets.all(10),
                        child: ListView.builder(
                            itemCount: list.length,
                            itemBuilder: (c, i) {
                              return Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 5, vertical: 3),
                                child: InkWell(
                                  onTap: () async {
                                    GroupBean2? bean =
                                        await MessageApi.getRoomMsg(
                                            roomId: "${list[i].id}");
                                    if (bean != null) {
                                      var controller = TextEditingController();
                                      String? password = await showDialog(
                                          context: context,
                                          builder: (c) => WillPopScope(
                                                onWillPop: () async {
                                                  return true;
                                                },
                                                child: AlertDialog(
                                                  title: const Text("请输入房间密码"),
                                                  content:
                                                      SingleChildScrollView(
                                                    child: Column(
                                                      children: [
                                                        TextField(
                                                          controller:
                                                              controller,
                                                          decoration:
                                                              const InputDecoration(
                                                                  hintText:
                                                                      "(无密码可为空)"),
                                                        ),
                                                        Row(
                                                          mainAxisAlignment:
                                                              MainAxisAlignment
                                                                  .end,
                                                          children: [
                                                            TextButton(
                                                                onPressed: () {
                                                                  Navigator.pop(
                                                                      context,
                                                                      controller
                                                                          .text);
                                                                },
                                                                child:
                                                                    const Text(
                                                                        "确定"))
                                                          ],
                                                        )
                                                      ],
                                                    ),
                                                  ),
                                                ),
                                              ));

                                      try {
                                        CommonLoading.show();
                                        await MessageApi.addGroup(
                                            roomId: "${bean.id}",
                                            userType: "普通用户",
                                            roomName: "${bean.roomName}",
                                            passwd: password ?? "");
                                        Navigator.pushReplacement(
                                            context,
                                            MaterialPageRoute(
                                                builder: (c) => ChatPage(
                                                    roomId: "${list[i].roomId}",
                                                    title:
                                                        "${list[i].roomName}")));
                                      } catch (e) {
                                        CommonLoading.hide();
                                      }
                                    }
                                  },
                                  child: Container(
                                    padding: const EdgeInsets.symmetric(
                                        horizontal: 10, vertical: 5),
                                    decoration: BoxDecoration(
                                        borderRadius: Constant.borderRadius,
                                        boxShadow: Constant.boxShadow,
                                        color: Colors.white),
                                    child: Row(
                                      children: [
                                        Container(
                                          padding: const EdgeInsets.all(15),
                                          decoration: const BoxDecoration(
                                              shape: BoxShape.circle,
                                              color: Colors.blue),
                                          child: Text(
                                            "${list[i].roomName}"
                                                .substring(0, 1),
                                            style: const TextStyle(
                                                color: Colors.white,
                                                fontSize: 18),
                                          ),
                                        ),
                                        const SizedBox(
                                          width: 10,
                                        ),
                                        Text("${list[i].roomName}")
                                      ],
                                    ),
                                  ),
                                ),
                              );
                            }),
                      ))
          ],
        ),
      ),
    );
  }

  Future<void> refresh() async {
    try {
      // CommonLoading.show();
      var l = await MessageApi.getAllGroups();
      if (l != null) {
        list.addAll(l);
      }
      setState(() {});
      // CommonLoading.hide();
    } catch (e) {
      // CommonLoading.hide();
      print(e);
    }
  }
}
